As a server admin, often times you will want to implement a script that will kill long SQL queries - queries that cause table locks that build up requests, eventually using up all the available connections and bring down the server.
Code:
<?php
/*
Cutoff controls how many seconds an sql query must be running before we're allowed to kill it.
A value of 0 will kill ALL threads.
It's wise to set this number to the same value you use in your cron job.
*/
$cutoff = 60;
/*
A list of thread IDs that you wish to NOT kill. This is useful if you have a mysqldump running
of if you have a service with a persistent mysql connection running on your machine.
*/
$protected_pids = array();
/*
To keep the script from killing processes belonging to a particular database, use this. Also
useful if you wish to spare a service from having it's connection killed.
*/
$protected_dbs = array();
$DB_HOST = 'localhost';
$DB_USERNAME = 'root';
$DB_PASSWORD = 'yourpassword';
mysql_connect($DB_HOST, $DB_USERNAME, $DB_PASSWORD) or die('Connection could not be made');
$result = mysql_query("SHOW FULL PROCESSLIST");
while ($row=mysql_fetch_array($result)) {
$process_id=$row["Id"];
if ($row["Time"] > $cutoff && !(in_array($row['db'],$protected_dbs)) && !(in_array($protected_pids,$row['Id']))) {
$fh = fopen(getcwd().'/sqlkill_log.log','a');
fwrite($fh,'Killed process '.$process_id.' at: '.date('H:i:s, Y-m-d',time())."\n".
'Query: '.$row['Info'])."\n\n";
$sql="KILL $process_id";
mysql_query($sql);
fclose($fh);
}
}
?>
Just add it to your crontab. I have mine run once ever 60 seconds.